import tkinter as tk
import random
import time
from PIL import Image, ImageTk, ImageDraw


class RoundedMessage:
    def __init__(self, root, text, color):
        self.root = root
        self.text = text
        self.color = color

        # 创建消息框
        self.window = tk.Toplevel(root)
        self.window.geometry(f"240x140+{random.randint(100, 1200)}+{random.randint(100, 800)}")
        self.window.overrideredirect(True)  # 移除窗口边框
        self.window.attributes('-topmost', True)  # 置顶

        # 创建一个画布来实现圆角效果
        self.canvas = tk.Canvas(self.window, width=240, height=140, highlightthickness=0)
        self.canvas.pack(fill="both", expand=True)

        # 创建圆角背景图像
        self.bg_image = self.create_rounded_rectangle(240, 140, 25, self.color)
        self.bg_photo = ImageTk.PhotoImage(self.bg_image)
        self.canvas.create_image(0, 0, anchor="nw", image=self.bg_photo)

        # 创建标题栏
        self.title_bar = tk.Frame(self.window, bg='white', height=28)
        self.title_bar.place(x=1, y=1, width=238, height=28)

        # 窗口控制按钮
        self.controls_frame = tk.Frame(self.title_bar, bg='white')
        self.controls_frame.pack(side='left', padx=5)

        # 关闭按钮
        self.close_btn = tk.Label(self.controls_frame, text="×", bg='#ff5f57', fg='black',
                                  font=('Arial', 8, 'bold'), width=2, height=1, relief='raised', bd=1)
        self.close_btn.pack(side='left', padx=2)
        self.close_btn.bind('<Button-1>', lambda e: self.window.destroy())

        # 最小化按钮 (仅样式)
        self.minimize_btn = tk.Label(self.controls_frame, text="−", bg='#febb2e', fg='black',
                                     font=('Arial', 8, 'bold'), width=2, height=1, relief='raised', bd=1)
        self.minimize_btn.pack(side='left', padx=2)

        # 最大化按钮 (仅样式)
        self.maximize_btn = tk.Label(self.controls_frame, text="□", bg='#28c840', fg='black',
                                     font=('Arial', 8, 'bold'), width=2, height=1, relief='raised', bd=1)
        self.maximize_btn.pack(side='left', padx=2)

        # 标题文本
        self.title_label = tk.Label(self.title_bar, text="爱你", bg='white', fg='#555555',
                                    font=('Arial', 10, 'bold'))
        self.title_label.pack(side='left', padx=10)

        # 消息内容区域
        self.message_frame = tk.Frame(self.window, bg=self.color)
        self.message_frame.place(x=1, y=30, width=238, height=109)

        # 消息内容
        self.message_label = tk.Label(self.message_frame, text=self.text, bg=self.color,
                                      fg='#444444', font=('Arial', 12, 'bold'),
                                      wraplength=200, justify='center')
        self.message_label.pack(expand=True, fill='both', padx=10, pady=10)

        # 设置窗口位置和大小
        self.window.update_idletasks()

        # 添加鼠标拖动功能
        self.title_bar.bind('<ButtonPress-1>', self.start_move)
        self.title_bar.bind('<B1-Motion>', self.move_window)

        # 添加悬停效果
        self.window.bind('<Enter>', self.on_enter)
        self.window.bind('<Leave>', self.on_leave)

        # 使用 after() 方法实现定时器，避免多线程问题
        self.start_moving()

    def create_rounded_rectangle(self, width, height, radius, color):
        """使用PIL创建圆角矩形图像"""
        image = Image.new('RGBA', (width, height), (0, 0, 0, 0))
        draw = ImageDraw.Draw(image)

        # 将十六进制颜色转换为RGB
        if color.startswith('#'):
            r = int(color[1:3], 16)
            g = int(color[3:5], 16)
            b = int(color[5:7], 16)
        else:
            r, g, b = 255, 255, 255

        # 绘制圆角矩形
        draw.rounded_rectangle([0, 0, width - 1, height - 1],
                              radius=radius,
                              fill=(r, g, b, 255),
                              outline=(200, 200, 200, 255),
                              width=1)

        return image

    def on_enter(self, event):
        """鼠标进入窗口时的效果"""
        # 创建高亮边框图像
        highlight_image = self.create_rounded_rectangle(240, 140, 25, self.color)
        draw = ImageDraw.Draw(highlight_image)
        draw.rounded_rectangle([0, 0, 239, 139], radius=25, outline=(100, 100, 100, 255), width=2)

        self.highlight_photo = ImageTk.PhotoImage(highlight_image)
        self.canvas.create_image(0, 0, anchor="nw", image=self.highlight_photo)

    def on_leave(self, event):
        """鼠标离开窗口时的效果"""
        # 恢复普通边框
        self.canvas.create_image(0, 0, anchor="nw", image=self.bg_photo)

    def start_moving(self):
        """开始随机移动"""
        self.random_move()

    def random_move(self):
        """随机移动窗口"""
        if self.window.winfo_exists():
            new_x = random.randint(50, 1200)
            new_y = random.randint(50, 800)
            self.window.geometry(f"240x140+{new_x}+{new_y}")

            # 使用 after() 方法安排下一次移动
            self.window.after(3000, self.random_move)

    def start_move(self, event):
        """开始拖动"""
        self.x = event.x
        self.y = event.y

    def move_window(self, event):
        """移动窗口"""
        dx = event.x - self.x
        dy = event.y - self.y
        x = self.window.winfo_x() + dx
        y = self.window.winfo_y() + dy
        self.window.geometry(f"+{x}+{y}")

        self.x = event.x
        self.y = event.y


def create_floating_messages():
    """创建多个浮动消息"""
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    # 定义消息内容
    messages = [
        "我想你了", "好好吃饭!", "记得加衣!", "天天开心", "期待下一次见面",
        "愿所有烦恼都消失", "记得照顾好自己", "别感冒", "世界上最后一个纯爱",
        "遇见你是浪漫的开始"
    ]

    # 使用柔和的便签颜色
    colors = [
        '#ffe0e3', '#c7f0ff', '#ffd8a8', '#d9f2d9', '#e5d7ff',
        '#f9f7d9', '#d2f0f8', '#ffd4f5', '#e3ffe3', '#ffe8d6'
    ]

    # 存储所有消息框的列表
    message_windows = []

    # 10秒后自动结束
    end_time = time.time() + 10

    # 创建消息框的函数
    def create_message():
        nonlocal message_windows
        if len(message_windows) >= 30:
            # 如果超过30个，移除最旧的一个
            oldest_window = message_windows.pop(0)
            oldest_window.window.destroy()

        # 创建新的消息框
        message = random.choice(messages)
        color = random.choice(colors)
        new_message = RoundedMessage(root, message, color)
        message_windows.append(new_message)

        # 安排下一个消息创建
        if time.time() < end_time:
            root.after(200, create_message)  # 每200毫秒创建一个消息

    # 开始创建消息
    root.after(100, create_message)  # 延迟100毫秒开始

    # 10秒后结束程序
    def check_end():
        if time.time() >= end_time:
            root.quit()
        else:
            root.after(1000, check_end)  # 每秒检查一次

    root.after(1000, check_end)

    # 保持程序运行
    try:
        root.mainloop()
    except:
        pass


if __name__ == "__main__":
    create_floating_messages()
